package com.rzico.sbl.ui.report

import android.text.Editable
import android.text.TextWatcher
import android.view.MotionEvent
import android.widget.CompoundButton
import android.widget.EditText
import android.widget.ImageView
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.LiveEventBus
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportCarBinding
import com.rzico.sbl.model.ReportCarData
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.listener._TextWatcher
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.setCompoundDrawable
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONArray
import org.json.JSONObject

class ReportCarActivity : BaseActivity(R.layout.activity_report_car) {

    private val mBinding by lazy { ActivityReportCarBinding.bind(getRootView()) }
    private val mCarList = ArrayList<ReportCarData>()

    override fun initData() {
        initTitle(title = "购物车")

        initLayout()

        mCarList.addItems(intent.getParcelableArrayListExtra("data"))
        mAdapter.setDataList(mCarList)

        mBinding.carAll.isChecked = mCarList.isNotEmpty() && mCarList.none { !it.check }
        mBinding.carAll.setOnCheckedChangeListener(this@ReportCarActivity)

        mBinding
            .listLayout
            .emptyLayout
            .emptyView
            .isVisible = mCarList.isEmpty()
    }

    private fun initLayout() {
        mBinding.carAll.setCompoundDrawable(
            leftSize = 16f,
            leftDrawable = R.drawable.address_default_selector
        )

        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关商品信息！"
            }

            recycleList.also { layout ->
                layout.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = {
                        window
                            .decorView
                            .postDelayed({
                                mAdapter.notifyDataSetChanged()
                                swipeRefresh.isRefreshing = false
                            }, 1500)
                    }
                )

                layout.addItemDecoration(SpaceTBDecoration())

                mAdapter = SlimAdapter.creator()
                    .register<ReportCarData>(R.layout.item_report_car) { jector, bean, index ->
                        jector.apply {
                            gone(R.id.item_car_hint)
                            text(R.id.item_car_name, bean.name)
                            text(R.id.item_car_price, bean.phPrice.formatDecimal())
                            with<ImageView>(R.id.item_car_img) {
                                it.loadImage(bean.thumbnail)
                            }
                            image(
                                R.id.item_car_check,
                                if (bean.check) R.mipmap.login_yes_orange else R.mipmap.login_no
                            )
                            with<EditText>(R.id.item_car_input) {
                                if (it.tag != null && it.tag is TextWatcher) {
                                    it.removeTextChangedListener(it.tag as TextWatcher)
                                }

                                it.setText(bean.input)
                                it.setSelection(it.text.length)

                                val textWatcher = object : _TextWatcher() {
                                    override fun afterTextChanged(s: Editable) {
                                        bean.input = s.toString()
                                    }
                                }
                                it.addTextChangedListener(textWatcher)
                                it.tag = textWatcher
                            }
                            clicked {
                                bean.check = !bean.check
                                notifyItemChanged(index)

                                mBinding.carAll.setOnCheckedChangeListener(null)
                                mBinding.carAll.isChecked = mCarList.none { !it.check }
                                mBinding.carAll.setOnCheckedChangeListener(this@ReportCarActivity)
                            }
                        }
                    }
                    .attachTo(layout)
            }
        }
    }

    override fun initListener() {
        mBinding.apply {
            // 当列表为空时，拦截事件
            carAll.oneTouch(
                handle = { mCarList.isEmpty() && it.action == MotionEvent.ACTION_UP }
            )

            carDel.oneClick {
                if (mCarList.any { it.check }) {
                    showHintDialog(
                        hint = "确定要删除商品吗？",
                        onSure = {
                            val listId = ArrayList<String>()
                            mCarList.filter { it.check }.mapTo(listId) { it.id }

                            mCarList.removeAll { it.check }
                            mAdapter.notifyDataSetChanged()

                            listLayout
                                .emptyLayout
                                .emptyView.isVisible = mCarList.isEmpty()

                            carAll.setOnCheckedChangeListener(null)
                            carAll.isChecked = mCarList.isNotEmpty() && mCarList.none { !it.check }
                            carAll.setOnCheckedChangeListener(this@ReportCarActivity)

                            LiveEventBus
                                .get("carList")
                                .post(listId.joinToString(","))
                        }
                    )
                } else showToast("请选择要删除的商品")
            }

            carSure.oneClick {
                if (mCarList.any { it.check }) {
                    val objArr = JSONArray()

                    mCarList
                        .filter { it.check }
                        .forEach {
                            if (it.input.intValue == 0) {
                                showToast("${it.name} 商品数量不能小于0")
                                return@oneClick
                            }

                            val obj = JSONObject()
                            obj.put("id", it.id)
                            obj.put("quantity", it.input)

                            objArr.put(obj)
                        }

                    startActivityEx<ReportBookActivity>(
                        "orderSn" to intent.getExtra("orderSn"),
                        "body" to objArr.toString()
                    )
                } else showToast("请选择要结算的商品")
            }
        }
    }

    override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
        mCarList.forEach { it.check = isChecked }
        mAdapter.notifyDataSetChanged()
    }

}